/** *******************************************************************
 * FlexDatabaseManager
 * Copyright (c) 2008 Jonnie Spratley. All Rights Reserved.
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.tables
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.commands.SequenceCommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.tables.ShowTableStatusEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class ShowTableStatusCommand extends SequenceCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		override public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			
			var evt:ShowTableStatusEvent = event as ShowTableStatusEvent;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
			
			if ( model.selectedDatabase == null )
			{
				//alert the user and don't get the data.
				Alert.show( 'Please select a database first.', 'Alert' );
				return;
				
			} else {
				//get the table status
				//delegate.showTableStatus( model.currentUser, model.selectedDatabase );
			}	
		}
		
		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var resultObj:ResultEvent = data as ResultEvent;
			
			if ( resultObj.result is String )
			{
				var rawData:String = String( resultObj.result ); 
				var tempArray:Array = ( JSON.decode( rawData ) as Array );
				
				for ( var s:String in tempArray )
				{		
					tempArray.push( new TableStatusVO( tempArray[s] ) );	
				}
				model.tableStatusCollection = new ArrayCollection( tempArray );
			}
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			
			Alert.show(faultEvt.fault.toString(), "Service Error");
			trace(faultEvt.fault.faultString);
		}

	}
}
